package com.jack.helloworld.liveWallpaper;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jack.helloworld.R;
import com.jack.helloworld.util.Constants;
import com.jack.helloworld.util.SharedPreferenceHelper;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

public class VideoLiveWallPaperLoaderActivity extends Activity {

    private GridView mGvVideoThumbnail;
    private VideoLiveWallPaperLoaderGridViewAdapter mVideoLoaderGridViewAdapter;
    private List<VideoInfo> mVideoList = new ArrayList<VideoInfo>();

    private ImageButton mIbVideoLiveWallpaperVoice;

    private ProgressDialog mProgressDialog;
    private boolean hasVoice = false;

    private ExitReceiver exitReceiver = new ExitReceiver();

    private static final int SCAN_OK = 0x01;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SCAN_OK:
                    mProgressDialog.dismiss();

                    dataToView();

                    break;
            }
        }
    };

    private void dataToView() {

        if (mVideoList.isEmpty()) {
            Toast.makeText(VideoLiveWallPaperLoaderActivity.this, R.string.no_video_scaned, Toast.LENGTH_SHORT).show();
        }

        for (int index = 0; index < mVideoList.size(); index++) {
            Logger.d("[index=" + index + "],getThumbPath:" + mVideoList.get(index).toString());
        }

        mVideoLoaderGridViewAdapter = new VideoLiveWallPaperLoaderGridViewAdapter();
        mGvVideoThumbnail.setAdapter(mVideoLoaderGridViewAdapter);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_live_wallpaper_loader);

        initView();
        initData();
        initEvent();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(exitReceiver);
    }

    private void initEvent() {

        initExitEvent();

        mGvVideoThumbnail.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Logger.d("click:" + position + " ,mVideoList.get(position):" + mVideoList.get(position).toString());
                SharedPreferenceHelper.write(VideoLiveWallPaperLoaderActivity.this,
                        Constants.SP_LIVE_WALLPAPER,
                        Constants.SP_LIVE_WALLPAPER_KEY_URI,
                        mVideoList.get(position).getPath());

                Intent intent = new Intent(VideoLiveWallPaperLoaderActivity.this, VideoLoaderActivity.class);
                intent.putExtra(Constants.SP_LIVE_WALLPAPER_KEY_URI, mVideoList.get(position).getPath());
                startActivity(intent);
            }
        });

        mIbVideoLiveWallpaperVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (hasVoice) {
                    hasVoice = false;
                    mIbVideoLiveWallpaperVoice.setImageResource(R.drawable.ic_volume_off_black_24dp);
                    VideoLiveWallpaperService.voiceNormal(VideoLiveWallPaperLoaderActivity.this);
                    SharedPreferenceHelper.write(VideoLiveWallPaperLoaderActivity.this,
                            Constants.SP_LIVE_WALLPAPER,
                            Constants.SP_LIVE_WALLPAPER_KEY_VOICE,
                            false);
                } else {
                    hasVoice = true;
                    mIbVideoLiveWallpaperVoice.setImageResource(R.drawable.ic_volume_up_black_24dp);
                    VideoLiveWallpaperService.voiceSilence(VideoLiveWallPaperLoaderActivity.this);
                    SharedPreferenceHelper.write(VideoLiveWallPaperLoaderActivity.this,
                            Constants.SP_LIVE_WALLPAPER,
                            Constants.SP_LIVE_WALLPAPER_KEY_VOICE,
                            true);
                }
            }
        });
    }


    private void initData() {
        scanVideo();
        initStatus();
    }

    private void initExitEvent() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.EXIT_ACTION);
        registerReceiver(exitReceiver, filter);
    }

    private void initStatus() {
        hasVoice = (boolean) SharedPreferenceHelper.read(this,
                Constants.SP_LIVE_WALLPAPER,
                Constants.SP_LIVE_WALLPAPER_KEY_VOICE,
                SharedPreferenceHelper.BOOLEAN_VALUE);
        if (hasVoice) {
            mIbVideoLiveWallpaperVoice.setImageResource(R.drawable.ic_volume_up_black_24dp);
        } else {
            mIbVideoLiveWallpaperVoice.setImageResource(R.drawable.ic_volume_off_black_24dp);
        }
    }

    private void scanVideo() {
        if (EasyPermissions.hasPermissions(this, Constants.PERMISSIONS_RW_EXTERNAL_STORAGE)) {
            //通过ContentProvider扫描所有图片
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                Toast.makeText(this, R.string.sdcard_unmounted, Toast.LENGTH_SHORT).show();
            }

            mProgressDialog = ProgressDialog.show(this, null, getString(R.string.video_loading));

            new Thread(new Runnable() {
                @Override
                public void run() {
                    String[] thumbColumns = {MediaStore.Video.Thumbnails.DATA,
                            MediaStore.Video.Thumbnails.VIDEO_ID};

                    // MediaStore.Video.Media.DATA：视频文件路径；
                    // MediaStore.Video.Media.DISPLAY_NAME : 视频文件名，如 testVideo.mp4
                    // MediaStore.Video.Media.TITLE: 视频标题 : testVideo
                    String[] mediaColumns = {MediaStore.Video.Media._ID,
                            MediaStore.Video.Media.DATA,
                            MediaStore.Video.Media.TITLE,
                            MediaStore.Video.Media.MIME_TYPE,
                            MediaStore.Video.Media.DISPLAY_NAME};

                    Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    ContentResolver cr = VideoLiveWallPaperLoaderActivity.this.getContentResolver();

                    Cursor cursor = cr.query(uri, mediaColumns, null, null, null);

                    if (cursor == null) {
                        return;
                    }

                    Cursor thumbCursor = null;

                    while (cursor.moveToNext()) {
                        VideoInfo videoInfo = new VideoInfo();

                        int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Media._ID));
                        thumbCursor = cr.query(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI, thumbColumns,
                                MediaStore.Video.Thumbnails.VIDEO_ID + "=" + id, null, null);

                        if (thumbCursor.moveToNext()) {
                            videoInfo.setThumbPath(thumbCursor.getString(thumbCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA)));
                        }
                        videoInfo.setPath(cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA)));
                        videoInfo.setTitle(cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE)));
                        videoInfo.setName(cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME)));
                        videoInfo.setMimeType(cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.MIME_TYPE)));

                        Logger.d(videoInfo.toString());

                        mVideoList.add(videoInfo);
                        thumbCursor.close();
                    }

                    handler.sendEmptyMessage(SCAN_OK);
                    cursor.close();
                }
            }).start();


        } else {
            // Ask for permissions
            EasyPermissions.requestPermissions(this, getString(R.string.request_read_storage_load_video),
                    Constants.REQUEST_CODE_PERMISSIONS_RW_EXTERNAL_STORAGE,
                    Constants.PERMISSIONS_RW_EXTERNAL_STORAGE);
        }
    }

    private void initView() {
        mGvVideoThumbnail = (GridView) findViewById(R.id.gv_video_thumbnail);
        mIbVideoLiveWallpaperVoice = (ImageButton) findViewById(R.id.ib_video_live_wallpaper_voice);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.LIVE_WALLPAPER_REQUEST_CODE) {
            finish();
        }
    }

    class ExitReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            VideoLiveWallPaperLoaderActivity.this.finish();
        }

    }



    class VideoLiveWallPaperLoaderGridViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mVideoList.size();
        }

        @Override
        public Object getItem(int position) {
            return mVideoList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            ViewHolder viewHolder;
            VideoInfo videoInfo = mVideoList.get(position);
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(VideoLiveWallPaperLoaderActivity.this).inflate(R.layout.video_loader_gridview_item, viewGroup, false);

                viewHolder.VideoLoaderThumbnailImageView = (ImageView) convertView.findViewById(R.id.iv_video_thumbnail);
                viewHolder.VideoLoaderThumbnailTextView = (TextView) convertView.findViewById(R.id.tv_video_thumbnail_name);

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.VideoLoaderThumbnailTextView.setText(videoInfo.getTitle());
            viewHolder.VideoLoaderThumbnailImageView.setImageResource(R.drawable.pictures_no);

            if (videoInfo.getThumbPath() == null || videoInfo.getThumbPath().isEmpty()) {
                Glide.with(VideoLiveWallPaperLoaderActivity.this).load(Uri.fromFile(new File(videoInfo.getPath()))).into(viewHolder.VideoLoaderThumbnailImageView);
            } else {
                Glide.with(VideoLiveWallPaperLoaderActivity.this).load(videoInfo.getThumbPath()).into(viewHolder.VideoLoaderThumbnailImageView);
            }

            return convertView;
        }


        private class ViewHolder {
            ImageView VideoLoaderThumbnailImageView;
            TextView VideoLoaderThumbnailTextView;
        }
    }
}
